/*ViewPhoto.java
 * 
 * Activity to view individual photo close up
 * 
 *  Shared Preferences code based on example from http://developer.android.com/guide/topics/data/data-storage.html
 *  Image view code based on http://developer.android.com/reference/android/widget/ImageView.html
 *  Alert dialog code based on example from http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/AlertDialogSamples.html
 *  
 */
package com.tagit;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.SlidingDrawer;
import android.widget.Toast;

public class ViewPhoto extends Activity {

	private PhotosDbAdapter mPhotoDb;
	public static final String PREFS_NAME = "MyPrefsFile";
	Button btDone;
	Button btReject;
	SharedPreferences settings;
	int numAlgos;

	private long mPhotoId;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mPhotoDb = new PhotosDbAdapter(this);
		mPhotoDb.open();
		setContentView(R.layout.viewphoto);
		ImageView image = (ImageView) findViewById(R.id.imageView);
		Bundle extras = getIntent().getExtras();
		mPhotoId = extras.getLong(PhotosDbAdapter.KEY_ID);
		String path = extras.getString(PhotosDbAdapter.KEY_URI);
		Bitmap bm = BitmapFactory.decodeFile(path);
		image.setImageBitmap(bm);

		// From
		// http://stackoverflow.com/questions/2795833/check-orientation-on-android-phone
		// Display getOrient = getWindowManager().getDefaultDisplay();
		Configuration config = getResources().getConfiguration();
		int orientation = config.orientation;

		// If orientation is portrait, can fill full screen
		if (orientation == Configuration.ORIENTATION_PORTRAIT) {
			image.setScaleType(ImageView.ScaleType.FIT_XY);
		} else {
			image.setScaleType(ImageView.ScaleType.CENTER_INSIDE); // Otherwise,
																	// crop and
																	// center
		}

		// Autocomplee for textbox
		List<String> listTags = mPhotoDb.getAllTags();
		if (!listTags.isEmpty()) {
			String[] allTags = listTags.toArray(new String[] {});
			AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_tags);
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					R.layout.list_tag, allTags);
			textView.setAdapter(adapter);
		}

		numAlgos = 0;
		settings = getSharedPreferences(PREFS_NAME, 0);

		// Initialize reject and done buttons
		btReject = (Button) findViewById(R.id.reject);
		btDone = (Button) findViewById(R.id.done);

		// Set listener for Done button
		btDone.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ViewPhoto.this, PhotoGallery.class);
				mPhotoDb.close();
				startActivity(intent);

			}
		});

		// Set listener for Reject button
		btReject.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				AlertDialog.Builder builder = createAlertDialog();
				AlertDialog alert = builder.create();
				alert.show();

			}
		});

		// Set listener for TagIt button
		Button addTag = (Button) findViewById(R.id.newtag_done);
		addTag.setOnClickListener(new View.OnClickListener() {

			// @Override
			public void onClick(View v) {
				AutoCompleteTextView new_tag = (AutoCompleteTextView) findViewById(R.id.autocomplete_tags);
				if (new_tag.getText().length() == 0) {
					// This is kind of bad since it actually the user clicked
					// add without entering anything in the box
					return;
				}
				String tag = new_tag.getText().toString();
				mPhotoDb.addTagToPhoto(mPhotoId, tag);
				new_tag.setText("");
				fill_tag_table();
			}
		});

		// Set the texts on the favorite tags buttons
		Button FT1button = (Button) findViewById(R.id.FT1);
		setButtonText(FT1button, 1);
		setSetFTClickListener(FT1button, 1);

		Button FT2button = (Button) findViewById(R.id.FT2);
		setButtonText(FT2button, 2);
		setSetFTClickListener(FT2button, 2);

		Button FT3button = (Button) findViewById(R.id.FT3);
		setButtonText(FT3button, 3);
		setSetFTClickListener(FT3button, 3);

		Button FT4button = (Button) findViewById(R.id.FT4);
		setButtonText(FT4button, 4);
		setSetFTClickListener(FT4button, 4);

		Button FT5button = (Button) findViewById(R.id.FT5);
		setButtonText(FT5button, 5);
		setSetFTClickListener(FT5button, 5);

		Button FT6button = (Button) findViewById(R.id.FT6);
		setButtonText(FT6button, 6);
		setSetFTClickListener(FT6button, 6);

		Button tagMenuDoneButton = (Button) findViewById(R.id.tag_menu_done);
		setTagMenuDoneClickListener(tagMenuDoneButton);

		fill_tag_table();
		setSetFTClickListener();
	}

	// Method to set text on buttons when user comes back from configure menu
	@Override
	protected void onResume() {
		super.onResume();
		Button FT1button = (Button) findViewById(R.id.FT1);
		setButtonText(FT1button, 1);

		Button FT2button = (Button) findViewById(R.id.FT2);
		setButtonText(FT2button, 2);

		Button FT3button = (Button) findViewById(R.id.FT3);
		setButtonText(FT3button, 3);

		Button FT4button = (Button) findViewById(R.id.FT4);
		setButtonText(FT4button, 4);

		Button FT5button = (Button) findViewById(R.id.FT5);
		setButtonText(FT5button, 5);

		Button FT6button = (Button) findViewById(R.id.FT6);
		setButtonText(FT6button, 6);

	}

	// Helper thod to set text on buttons
	public void setButtonText(Button button, int num) {
		numAlgos = 0;
		button.setText(getButtonText(button, num));
	}

	public String getButtonText(Button button, int num) {
		String text = new String();
		String favKey = Integer.toString(num) + "F";
		String algoKey = Integer.toString(num) + "A";
		String favString = Integer.toString(num) + "S";

		boolean fav = settings.getBoolean(favKey, false);
		boolean algo = settings.getBoolean(algoKey, false);

		// Get the stored strings for buttons or generate
		if (fav) {
			text = settings.getString(favString, "?");
		} else if (algo) {
			PhotosDbAdapter mDb = new PhotosDbAdapter(this);
			mDb.open();
			final List<String> tags = mDb.getAllTags();

			int index = tags.size();
			if (index <= numAlgos) {
				text = "tree"; // If not enough tags yet, tree is nice
			} else {
				text = tags.get(numAlgos);
				numAlgos++;
			}
		} else {
			text = "?";
		}
		return text;
	}

	private void CreateMenu(Menu menu) {
		menu.setQwertyMode(true);
		MenuItem mnu1 = menu.add(0, 0, 0, "Preferences");
		{
			mnu1.setAlphabeticShortcut('a');
		}
		MenuItem mnu2 = menu.add(0, 1, 1, "Help");
		{
			mnu2.setAlphabeticShortcut('b');
		}
	}

	private boolean MenuChoice(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			goToPreferences();
			return true;
		case 1:
			goToHelp();
			return true;
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		CreateMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return MenuChoice(item);
	}

	public void goToPreferences() {
		Intent intent = new Intent(ViewPhoto.this, Preferences.class);
		startActivity(intent);
	}

	public void goToHelp() {
		Intent intent = new Intent(ViewPhoto.this, Help.class);
		startActivity(intent);
	}

	// Method to create a confirmation method to reject a picture
	private AlertDialog.Builder createAlertDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to reject the picture?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								mPhotoDb.rejectPhoto(mPhotoId);
								Intent intent = new Intent(ViewPhoto.this,
										PhotoGallery.class);
								startActivity(intent);

								// Toast message to let know the user he is on
								// select mode
								Context context = getApplicationContext();
								CharSequence text = "You just rejected a picture";
								int duration = Toast.LENGTH_LONG;
								Toast toast = Toast.makeText(context, text,
										duration);
								toast.show();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		return builder;
	}

	public void fill_tag_table() {
		Cursor c = mPhotoDb.getTags(mPhotoId);
		GridView grid = (GridView) findViewById(R.id.gridview_existingtags);

		grid.setAdapter(new TagCursorAdapter(c, this));

		String[] from = new String[] { PhotosDbAdapter.KEY_TAG_CONTENT };
		int[] to = new int[] { R.id.tag1 };

		AbsListView listV = (AbsListView) findViewById(R.id.tagList);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.tag_row, c, from, to);
		listV.setAdapter(adapter);
	}

	// Method for when a user clicks on the set favorite tags button
	public void setSetFTClickListener() {
		Button setFTButton = (Button) findViewById(R.id.setFT);
		setFTButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), FavoriteTags.class);
				startActivity(intent);
			}
		});
	}

	/*
	 * Method for when a user clicks on a FT button - sets a tag or directs the
	 * user to the config screen
	 */
	public void setSetFTClickListener(final Button b, final int num) {
		b.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String favKey = Integer.toString(num) + "F";
				String algoKey = Integer.toString(num) + "A";
				String favString = Integer.toString(num) + "S";

				boolean fav = settings.getBoolean(favKey, false);
				boolean algo = settings.getBoolean(algoKey, false);

				if (fav || algo) {
					String tag = getButtonText(b, num);
					mPhotoDb.addTagToPhoto(mPhotoId, tag);
					fill_tag_table();

				} else {
					Intent intent = new Intent(v.getContext(),
							FavoriteTags.class);
					startActivity(intent);
				}
			}
		});
	}

	// Listener for done button for tagging menu
	public void setTagMenuDoneClickListener(final Button b) {
		b.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				SlidingDrawer sd = (SlidingDrawer) findViewById(R.id.drawer);
				sd.close();
			}
		});
	}
}
